/*
 * @(#)org.example.groupchat 2020/3/26/0026
 *
 * Copy Right@ 人人译视界
 */


package org.example.groupchat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * <pre>
 * @author tuwei
 *
 * @version 0.9
 *
 * 修改版本: 0.9
 * 修改日期: 2020/3/26/0026
 * 修改人 :  tuwei
 * 修改说明: 初步完成
 * 复审人 ：
 * </pre>
 */
public class GroupChatClient {
	private final static String HOST = "127.0.0.1";
	private final static int PORT = 6667;
	private Selector selector;
	private SocketChannel socketChannel;
	private String username;

	public GroupChatClient() {
		try {
			selector = Selector.open();
			socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
			socketChannel.configureBlocking(false);
			socketChannel.register(selector, SelectionKey.OP_READ);
			username = socketChannel.getLocalAddress().toString().substring(1);
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}


	public void sendInfo(String info) {
		info = username + "说：" + info;
		try {
			socketChannel.write(ByteBuffer.wrap(info.getBytes()));
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void readInfo() {
		try {
			int read = selector.select();
			if (read > 0) {
				Iterator<SelectionKey> ite = selector.selectedKeys().iterator();
				while (ite.hasNext()) {
					SelectionKey key = ite.next();
					if (key.isReadable()) {
						SocketChannel channel = (SocketChannel) key.channel();
						ByteBuffer buffer = ByteBuffer.allocate(1024);
						channel.read(buffer);
						String message = new String(buffer.array(), "utf-8");
						System.out.println("从服务器端获取消息：" + message);
					}
					ite.remove();
				}
			}
			else {
				System.out.println("没有可用的通道");
			}
		}
		catch(IOException e) {
			e.printStackTrace();
		}
	}

	public static void main(String[] args) {
		GroupChatClient groupChatClient = new GroupChatClient();
		new Thread() {
			public void run() {
				while(true) {
					groupChatClient.readInfo();
					try {
						Thread.currentThread().sleep(3000);
					}catch (Exception e) {
						e.printStackTrace();
					}
				}
			}
		}.start();

		Scanner scanner = new Scanner(System.in);
		while(scanner.hasNextLine()) {
			String s = scanner.nextLine();
			groupChatClient.sendInfo(s);
		}
	}
}
